package com.zzyl.nursing.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.framework.config.properties.WechatProperties;
import com.zzyl.nursing.service.WechatService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author robin
 * @date 25.5.26 10:48
 */
@Service
@RequiredArgsConstructor
public class WechatServiceImpl implements WechatService {
    // 本质是有参构造依赖注入：给成员变量赋值
    private final WechatProperties wechatProperties;

    @Override
    public String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, Object> paramMap = MapUtil.<String, Object>builder()
                .put("appid", wechatProperties.getAppId())
                .put("secret", wechatProperties.getAppSecret())
                .put("js_code", code)
                .put("grant_type", "authorization_code")
                .build();
        String result = HttpUtil.get(url, paramMap);
        JSONObject resultObj = JSONUtil.parseObj(result);
        if (resultObj.containsKey("errcode")) {
            throw new ServiceException("获取失败");
        }
        String openid = resultObj.getStr("openid");
        return openid;
    }

    @Override
    public String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, Object> paramMap = MapUtil.<String, Object>builder()
                .put("appid", wechatProperties.getAppId())
                .put("secret", wechatProperties.getAppSecret())
                .put("grant_type", "client_credential")
                .build();
        String result = HttpUtil.get(url, paramMap);
        JSONObject resultObj = JSONUtil.parseObj(result);
        if (resultObj.containsKey("errcode")) {
            throw new ServiceException("获取失败");
        }
        String accessToken = resultObj.getStr("access_token");
        return accessToken;
    }

    @Override
    public String getPhoneNumber(String accessToken, String phoneCode, String openId) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        Map<String, Object> resultMap = MapUtil.<String, Object>builder()
                .put("code", phoneCode)
                .put("openid", openId)
                .build();
        String jsonMap = JSONUtil.toJsonStr(resultMap);
        String jsonResult = HttpUtil.post(url, jsonMap);
        JSONObject jsonObject = JSONUtil.parseObj(jsonResult);
        if (jsonObject.getInt("errcode") != 0) {
            throw new ServiceException("获取接口错误");
        }
        JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
        String phoneNumber = phoneInfo.getStr("phoneNumber");
        return phoneNumber;
    }
}
